<?php
namespace app\admin\controller;
use think\Db;
use think\facade\Request;
use app\admin\controller\Calculate;
class Performance extends Common
{

    /**
     * @return array|mixed
     * @throws \think\exception\DbException
     */
    public function lists(){

        if (request()->isAjax()) {

            $keyword = input('post.keyword');
            $page =input('page',1);
            $pageSize =input('limit',config('pageSize'));

            $list = Db::name('performance')
                ->where('is_del',0)
                ->where('title', 'like', "%" . $keyword . "%")
                ->order('create_time desc')
                ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
                ->toArray();

            if (!empty($list)) {
                foreach ($list['data'] as $k => $v) {
                    $list['data'][$k]['create_time'] = toDate($v['create_time']);
                }
            }

            return $result = ['code'=>0,'msg'=>'成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1];
        }

        return $this->fetch('lists');
    }



    public function performanceAdd(){

        if(Request::isAjax()){

            $data = input('post.');

            if((!isset($data['title']))||$data['title']==''){
                $this->error('考核项名称不能为空!');
            }

            $dd = Db::name('performance')->where('title',$data['title'])->where('is_del',0)->find();

            if($dd){
                $this->error('该考核项已存在!');
            }

            if((!isset($data['var_content']))||(!$data['var_content'])){
                $this->error('请完善所有变量描述及分值!');
            }

            $var_content = [];
            $equation = '';

            foreach ($data['var_content'] as $k=>$v){

                $var = '$'.chr($k+97);
                $var_content[$var] = $v['des'];
                $equation .= $v['operator'].(float)$v['score'].'*'.$var;
                $var_content_key[] = $var;

            }

            $data["var_content"] = json_encode($var_content);
            $data["equation"] = $equation;
            $data["add_parentname"] = session('username');
            $data["create_time"] = time();
            $insID = Db::name('performance')->insertGetId($data);

            $log = [
                'content'=>'添加考核项'.$data['title']
            ];
            $wed = new Weblog();
            $res = $wed->insert($log);

            if ($insID && $res) {
                $var_content_key = implode(',',$var_content_key);
                $aa="public  function   timu$insID($var_content_key){ return  $equation; }\n}";
                $this->delLastLine($aa);
                $this->success('考核项添加成功',url('lists'),$insID);
            }else {
                $this->error('考核项添加失败!');
            }
        }else{
            return view('performanceForm');

        }

    }

    public function performanceEdit(){

        $title_id = input('title_id');
        if(Request::isAjax()){
            $data = input('post.');

            if((!isset($data['title']))||$data['title']==''){
                $this->error('考核项名称不能为空!');
            }

            $old_data = Db::name('performance')->where('title',$data['title'])->where('is_del',0)->find();

            if($old_data&&$old_data['title_id']!=$title_id){
                $this->error('该考核项已存在!');
            }

            if((!isset($data['var_content']))||(!$data['var_content'])){
                $this->error('请完善所有变量描述及分值!');
            }

            $var_content = [];
            $equation = '';

            foreach ($data['var_content'] as $k=>$v){

                $var = '$'.chr($k+97);
                $var_content[$var] = $v['des'];
                $equation .= $v['operator'].(float)$v['score'].'*'.$var;
                $var_content_key[] = $var;

            }

            //用于函数生成
            $var_content_key = implode(',',$var_content_key);

            $data["var_content"] = json_encode($var_content);
            $data["equation"] = $equation;


            $re = Db::name('performance')->where('title_id',$title_id)->update($data);
            $old_var_content_key = implode(',',array_keys( json_decode($old_data["var_content"],true)));
            $old_equation = $old_data["equation"];
            $log = [
                'content'=>'编辑考核项'.$data['title']
            ];
            $wed = new Weblog();
            $res = $wed->insert($log);

            if ($re!==false && $res) {

                $old_aa = "public  function   timu$title_id($old_var_content_key){ return  $old_equation; } \n";
                $aa="public  function   timu$title_id($var_content_key){ return  $equation; } \n";
                $this->replaceLastLine($old_aa,$aa);
                $this->success('考核项编辑成功',url('lists'));
            }else {
                $this->error('考核项编辑失败!');
            }
        }else{
            $performance_data = Db::name('performance')->where('title_id',$title_id)->find();

            $performance_data['var_content'] = json_decode($performance_data['var_content'],true);

            $count = count($performance_data['var_content']);

            $exp = explode('$',$performance_data['equation']);

            if(!empty($exp)){

                $tt = array();

                foreach ($exp as $k=>$v){

                    if($k==0){

                        $tt[$k]['op'] = substr($v,0,1);
                        $tt[$k]['score'] = substr($v,1,-1);

                    }elseif ($k<$count){
                        $tt[$k]['op'] = substr($v,1,1);
                        $tt[$k]['score'] = substr($v,2,-1);
                    }

                }

                $i  = 0;
                foreach ($performance_data['var_content'] as $k=>$v){

                    $temp[$v] = $tt[$i];
                    $i++;

                }

                $performance_data['var_content'] = $temp;

            }

            $this->assign('performance_data',$performance_data);
            $this->assign('count',$count);
            $this->assign('info',json_encode($performance_data,true));
            return view('performanceEdit');

        }

    }

    public function performanceDel(){

        $title_id = input('post.title_id');

        if (session('aid')==1){

            Db::name('performance')->where('title_id', $title_id)->update(['is_del' => 1]);

            $title = Db::name('performance')->where('title_id', $title_id)->value('title');

            $log = [
                'content'=>'删除考核项'.$title
            ];
            $wed = new Weblog();
            $wed->insert($log);

            return $result = ['code'=>1,'msg'=>'删除成功!'];

        }else{

            return $result = ['code'=>0,'msg'=>'您没有删除考核项的权限!'];

        }
    }

    /**
     * 生成函数
     * @param $append
     * @param string $file_path
     */

    public function delLastLine($append,$file_path="../application/admin/controller/Calculate.php"){
        $file = $fp = fopen($file_path, 'r') or die("Unable to open file!");
        while(!feof($file)){
            $fp = fgets($file);
            if($fp!="}"){
                $content[] = $fp;
            }
        }
        array_push($content,$append);
        fclose($file);

        //重新写入文件
        $file = fopen($file_path, 'w+');
        fwrite($file, implode("", $content));
        fclose($file);
    }

    /**
     * 修改函数
     * @param $old_append
     * @param $append
     * @param string $file_path
     */
    public function replaceLastLine($old_append,$append,$file_path="../application/admin/controller/Calculate.php"){
        $file = $fp = fopen($file_path, 'r') or die("Unable to open file!");
        while(!feof($file)){
            $fp = fgets($file);

            if(trim($fp)==trim($old_append)){
                $content[] = $append;
            }else{
                $content[] = $fp;
            }

        }
        fclose($file);

        //重新写入文件
        $file = fopen($file_path, 'w+');
        fwrite($file, implode("", $content));
        fclose($file);
    }


    /**
     * * 计算分数及月度考核初始页面展示
     * @return \think\response\View
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */

    public function title(){

        if(Request::isAjax()) {

            //计算并保存考核项答案

            $cate_id = input('get.cate_id');
//            检查提交状态
            $submit_status = Db::name('answer_record')->where('teacher_id',session('aid'))->where('performance_cate_id',$cate_id)->value('submit_status');
            if(isset($submit_status) && $submit_status==2){
                $this->error('您已提交，无权修改');
            }
//          获取参数
            $data = input('post.');
//            计算总分
            $total_score = 0;
            $jisuan = new Calculate();
            foreach ($data as $key=>$val){
                $total_score += call_user_func_array(array($jisuan,$key),$val);
            }
//          数据处理
            $result['score'] = $total_score;

            $answer_data = array();
            foreach ($data as $k=>$v){
                $answer = array();
                $answer['tiu_id'] = substr($k,4);
                $answer['answer'] = $v;
                $answer_data[] = $answer;
            }
            $result['answer_content']=serialize($answer_data);

            $result['submit_status'] = input('get.flag');

//            判断是否为第一次编辑 是则插入数据库  否则更新数据
            if ($submit_status){
                $re = Db::name('answer_record')->where('teacher_id',session('aid'))->where('performance_cate_id',$cate_id)->update($result);
            }else{
                $result['performance_cate_id'] = $cate_id;
                $result['add_parentname'] = session('username');
                $result['teacher_id'] = session('aid');
                $result['add_time'] = time();
                $re = Db::name('answer_record')->insert($result);
            }
//          网站日志
            $title = Db::name('performance_cate')->where('cate_id',$result['performance_cate_id'])->value('title');
            $log = [
                'content'=>'保存考核项'.$title
            ];
            $wed = new Weblog();
            $res = $wed->insert($log);
//            返回计算结果
            if ($re && $res){

                $this->success('本次总分为：'.$total_score,'',input('get.tab'));
            }

        }else{

            if(session('aid')==1){
                $cate_list = Db::name('performance_cate')->where('cycle_id',1)->where('is_del',0)->field('cate_id,pid,title')->select();
            }else{
                //查找今日是否可以编辑月度考核项
                $time_diff = Db::name('cycle')->where('status',1)->where('id',1)->find();
                $today = (int)date("d",time());

                if($time_diff && (int)$time_diff['start_time']<=$today && (int)$time_diff['end_time']>=$today){

                    $position_ids = Db::name('teacher')->where('id',session('aid'))->value('position_id');

                    if($position_ids){
                        $str_position_ids = implode(',',array_keys(json_decode($position_ids,true)));
                    }

                    $performance_cate_ids = Db::name('teacher_position')->field('performance_cate_ids')->where('position_id','in',$str_position_ids)->select();

                    $str_performance_cate_ids = '';
                    if($performance_cate_ids){
                        foreach ($performance_cate_ids as $k=>$v){
                            if($v['performance_cate_ids']){
                                $str_performance_cate_ids .= ','.implode(',',array_filter(array_unique(unserialize($v['performance_cate_ids']))));
                            }

                        }
                    }
                    $str_performance_cate_ids = implode(',',array_filter(array_unique(explode(',',$str_performance_cate_ids))));
                    $cate_list = Db::name('performance_cate')->where('cycle_id',1)->where('cate_id','in',$str_performance_cate_ids)->where('is_del',0)->field('cate_id,pid,title')->select();

                }else{
                    $cate_list = '';
                }

            }

            $this->assign('cate_list',$cate_list);
            $this->assign('tab',1);
            return view('title');
        }
    }

    /** 学期考核初始页面展示
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */

    public function term_title(){
        if(session('aid')==1){
            $cate_list = Db::name('performance_cate')->where('cycle_id',2)->where('is_del',0)->field('cate_id,pid,title')->select();
        }else{
            //查找今日是否可以编辑学期考核项
            $time_diff = Db::name('cycle')->where('status',1)->where('id',2)->find();
            $today = date("m-d",time());

            if($time_diff && $time_diff['start_time'] && $time_diff['end_time']){

                $start_time = unserialize($time_diff['start_time']);
                $end_time = unserialize($time_diff['end_time']);

                if((($today>=$start_time[0])&&($today<=$end_time[0]))||(($today>=$start_time[1])&&($today<=$end_time[1]))){
                    $position_ids = Db::name('teacher')->where('id',session('aid'))->value('position_id');

                    if($position_ids){
                        $str_position_ids = implode(',',array_keys(json_decode($position_ids,true)));
                    }

                    $performance_cate_ids = Db::name('teacher_position')->field('performance_cate_ids')->where('position_id','in',$str_position_ids)->select();

                    $str_performance_cate_ids = '';
                    if($performance_cate_ids){
                        foreach ($performance_cate_ids as $k=>$v){
                            if($v['performance_cate_ids']){
                                $str_performance_cate_ids .= ','.implode(',',array_filter(array_unique(unserialize($v['performance_cate_ids']))));
                            }

                        }
                    }
                    $str_performance_cate_ids = implode(',',array_filter(array_unique(explode(',',$str_performance_cate_ids))));
                    $cate_list = Db::name('performance_cate')->where('cycle_id',2)->where('cate_id','in',$str_performance_cate_ids)->where('is_del',0)->field('cate_id,pid,title')->select();

                }else{
                    $cate_list = '';
                }


            }else{
                $cate_list = '';
            }

        }
        $this->assign('cate_list',$cate_list);
        $this->assign('tab',2);
        return view('title');

    }

    /** * * 年度考核初始页面展示
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */

    public function year_title(){
        if(session('aid')==1){
            $cate_list = Db::name('performance_cate')->where('cycle_id',3)->where('is_del',0)->field('cate_id,pid,title')->select();
        }else{
            //查找今日是否可以编辑年度考核项
            $time_diff = Db::name('cycle')->where('status',1)->where('id',3)->find();

            $today = date("m-d",time());

            if($time_diff && $time_diff['start_time'] && $time_diff['end_time']){

                if(($today>=$time_diff['start_time'])&&($today<=$time_diff['end_time'])){
                    $position_ids = Db::name('teacher')->where('id',session('aid'))->value('position_id');

                    if($position_ids){
                        $str_position_ids = implode(',',array_keys(json_decode($position_ids,true)));
                    }

                    $performance_cate_ids = Db::name('teacher_position')->field('performance_cate_ids')->where('position_id','in',$str_position_ids)->select();

                    $str_performance_cate_ids = '';
                    if($performance_cate_ids){
                        foreach ($performance_cate_ids as $k=>$v){
                            if($v['performance_cate_ids']){
                                $str_performance_cate_ids .= ','.implode(',',array_filter(array_unique(unserialize($v['performance_cate_ids']))));
                            }

                        }
                    }
                    $str_performance_cate_ids = implode(',',array_filter(array_unique(explode(',',$str_performance_cate_ids))));
                    $cate_list = Db::name('performance_cate')->where('cycle_id',3)->where('cate_id','in',$str_performance_cate_ids)->where('is_del',0)->field('cate_id,pid,title')->select();

                }else{
                    $cate_list = '';
                }


            }else{
                $cate_list = '';
            }

        }
        $this->assign('cate_list',$cate_list);
        $this->assign('tab',3);
        return view('title');

    }

    /**ajax请求对应考核项分类下的考核项数据
     * @return mixed|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function title_show(){

        if(Request::isAjax()) {
            $cate_id = input('cate_id');
            //拿到该考核项分类下的考核项
            $performance_ids = Db::name('performance_cate')->where('cate_id',$cate_id)->value('performance_ids');
            if(!$performance_ids){
                return json(['msg'=>'暂无数据','code'=>0]);
            }
            $performance_ids = implode(',',unserialize($performance_ids));
            //查找考核项并进行数据处理
            $list = Db::name('performance')->where('title_id','in',$performance_ids)->select();
            foreach ($list as $k=>$v){
                //没有做题时渲染考核项
                $list[$k]['answer'] = '';
                $list[$k]['var_content'] = json_decode($v['var_content'],true);
            }

            //通过$cate_id去数据库比对该教师是否已经做过了该题
            $info = Db::name('answer_record')->where('teacher_id',session('aid'))->where('performance_cate_id',$cate_id)->find();

            if (!empty($info)){
                $info['answer_content'] = unserialize($info['answer_content']);
            }

            //如果存在
            if($info['answer_content']){
                foreach ($list as $k=>$v){
                    foreach ($info['answer_content'] as $k1=>$v1){
                        if ($v['title_id'] == $v1['tiu_id']){
                            $list[$k]['answer'] = $v1['answer'];
                        }
                    }
                }
            }

            $data['list'] = $list;
            $data['code'] = 1;
            return json($data);
        }

        return $this->fetch('title');

    }



    /**
     * ******************************************************************************************************************
     */


    /**考核项分类列表
     * @return array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function cate(){
        if (request()->isAjax()) {

            if(session('cate_list')){
                return $result = ['code'=>0,'msg'=>'成功!','data'=>session('cate_list')];
            }else{
                $list = $this->showCate();

                if (! empty($list)) {

                    foreach ($list as $k => $v) {

                        $list[$k]['create_time'] = toDate($v['create_time']);
                        $list[$k]['cycle_id'] = Db::name('cycle')->where('id',$list[$k]['cycle_id'])->value('title');
                        $list[$k]['update_time'] = toDate($v['update_time']);
                    }
                    session('cate_list',$list);
                }

                return $result = ['code'=>0,'msg'=>'成功!','data'=>$list];
            }


        }

        return $this->fetch('cate');
    }

    /**
     * 无限极分类数据获取
     * @param int $pid
     * @param array $result
     * @param int $blank
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function showCate($pid=0,&$result=[],$blank=-1){

        $res = Db::name('performance_cate')->where('is_del',0)->where('pid',$pid)->select();

        $blank += 1;

        foreach ($res as $k=>$v){

            $v['title'] = str_repeat('|—',$blank).$v['title'];

            $result[] =$v;

            $this->showCate($v['cate_id'],$result,$blank);

        }

        return $result;

    }

    /**
     * 考核项分类添加
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */

    public function cateAdd(){

        if (request()->isAjax()) {

            $data = input('post.');
            $user = Db::name('performance_cate')->where(['title'=>$data['title']])->find();
            if($user){
                $this->error('该部门已存在');
            }
            $data['create_time'] = time();
            $data['update_time'] = time();
            $data['add_parentname'] = session('username');
            $re = Db::name('performance_cate')->insert($data);
            $log = [
                'content'=>'添加考核项分类'.$data['title']
            ];
            $wed = new Weblog();
            $wed->insert($log);
            if(!$re){
                $this->error('添加失败');
            }
            session('cate_list',null);
            $this->success("添加成功",'cate');

        }
        $cycle_list = Db::name('cycle')->select();
        $list = $this->showCate();
//        dump($list);die;
//        $list = Db::name('performance_cate')->where('is_del',0)->where('pid',0)->select();
        $this->assign('section',$list);
        $this->assign('cycle_list',$cycle_list);
        return $this->fetch('cate_add');

    }

    /**
     * 部门编辑
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function cateEdit(){

        $section_id = (int)input('section_id');
        if (request()->isAjax()) {

            $data = input('post.');
            $map[] = ['title','=',$data['title']];
            $map[] = ['cate_id','<>',$data['cate_id']];
            $user = Db::name('performance_cate')->where($map)->find();
            if($user){
                $this->error('该分类已存在');
            }
            $data['update_time'] = time();
            $data['add_parentname'] = session('username');
            $re = Db::name('performance_cate')->update($data);
            $log = [
                'content'=>'编辑考核项分类'.$data['title']
            ];
            $wed = new Weblog();
            $wed->insert($log);
            if(!$re){
                $this->error('编辑失败');
            }
            session('cate_list',null);
            $this->success("编辑成功",'cate');

        }

        $section_data = Db::name('performance_cate')->where('cate_id',$section_id)->find();
        $cycle_list = Db::name('cycle')->select();
        $this->assign('info',json_encode($section_data,true));
        $this->assign('section_data',$section_data);
        $this->assign('cycle_list',$cycle_list);
        return $this->fetch('cate_edit');

    }

    /**
     * 分类下考核项编辑
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function catePerformance(){

        $cate_id = (int)input('cate_id');

        if (request()->isAjax()) {

            $data = input('post.');

            $data['update_time'] = time();
            $data['performance_ids'] = serialize($data['performance_ids']);
            $re = Db::name('performance_cate')->update($data);
            $user = Db::name('performance_cate')->where(['cate_id'=>$data['cate_id']])->find();
            $log = [
                'content'=>'编辑考核项分类'.$user['title']
            ];

            $wed = new Weblog();
            $wed->insert($log);

            if(!$re){
                $this->error('编辑失败');
            }
            $this->success("编辑成功",'cate');

        }

        $timus = '';
        $user = Db::name('performance_cate')->where(['cate_id'=>$cate_id])->find();
        if($user['performance_ids']){
            $ids = implode(',',unserialize($user['performance_ids']));
            $timus = Db::name('performance')->field('title_id,title')->where('title_id','in',$ids)->select();
        }
        $this->assign('cate_id',$cate_id);
        $this->assign('timus',$timus);
        return $this->fetch('cate_performance');

    }

    /**删除考核项分类
     * URL：admin/section/sectionDel
     * @throws
     * @return array
     */
    public function cateDel(){

        $section_id = input('post.section_id');

        if (session('aid')==1){

            Db::name('performance_cate')->where('cate_id', $section_id)->update(['is_del' => 1,'update_time'=>time()]);

            $title = Db::name('performance_cate')->where('cate_id', $section_id)->value('title');

            $log = [
                'content'=>'删除考核项分类'.$title
            ];
            $wed = new Weblog();
            $wed->insert($log);
            session('cate_list',null);

            return $result = ['code'=>1,'msg'=>'删除成功!'];

        }else{

            return $result = ['code'=>0,'msg'=>'您没有删除分类的权限!'];

        }
    }


    /**个人绩效
     * @return array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function personList(){

        if (request()->isAjax()) {

            $page =input('page',1);
            $pageSize =input('limit',config('pageSize'));

            //部门id
            $post_section_id = (int)trim(input('post.section_id'));
            //教师关键字
            $teacher_keywoed = trim(input('post.teacher_keywoed'));
            //周期id
            $cycle_cate = (int)trim(input('post.cycle_cate'));
            //周期关键字1
            $c1 = trim(input('post.cycle_1'));
            //周期关键字2
            $c2 = trim(input('post.cycle_2'));

            if($post_section_id){
                $map['t.section_id'] = $post_section_id;
            }


//        当前月份一号
            $start_time = strtotime(date('Y-m',  time()).'-01');
//        当前时间
            $end_time = time();

            //月度
            if($cycle_cate==1){
                $cycle_data = Db::name('cycle')->where('id',1)->find();
                $start_time = strtotime($c1.'-'.$cycle_data['start_time']);
                $end = $c1.'-'.$cycle_data['end_time'];
                $end_time = strtotime( "$end +1 day");
//学期
            }elseif ($cycle_cate==2){

                $cycle_data = Db::name('cycle')->where('id',2)->find();
                $cycle_data_start_time = unserialize($cycle_data['start_time']);
                $cycle_data_end_time = unserialize($cycle_data['end_time']);
                $start_time = strtotime($c1.'-'.$cycle_data_start_time[$c2-1]);
                $end = $c1.'-'.$cycle_data_end_time[$c2-1];
                $end_time = strtotime( "$end +1 day");

//年度
            }elseif ($cycle_cate==3){
                $cycle_data = Db::name('cycle')->where('id',3)->find();
                $start_time = strtotime($c1.'-'.$cycle_data['start_time']);
                $end = $c1.'-'.$cycle_data['end_time'];
                $end_time = strtotime( "$end +1 day");

            }


            //拿到全部教师
            $teacher_data = Db::name('teacher t')
                ->join("section s", "s.section_id=t.section_id", 'left')
                ->field("t.id,t.teacher_no,t.true_name,t.position_id,s.title as section_name,s.section_id")
                ->where('t.is_del',0)
                ->where('t.id','neq',1)
                ->select();

            if(!$teacher_data){
                return $result = ['code' => 0, 'msg' => '成功!', 'data' => '', 'count' =>''];
            }

            //将id的值装换为key值
            foreach ($teacher_data as $k=>$v){

                $temp[$v['id']] = $v;

            }

            $count = count($teacher_data);
            $teacher_data['total'] = $count;
            $teacher_data['data'] = $temp;

            //考核项分类列表
            $cate_data =  Db::name('performance_cate')->field("cate_id,title,cycle_id")->where('is_del',0)->select();

            if(!$cate_data){
                return $result = ['code' => 0, 'msg' => '成功!', 'data' => $teacher_data['data'], 'count' =>$teacher_data['total']];
            }

            foreach ($teacher_data['data'] as $k=>$v){
                //职务数据
                $position = array_keys(json_decode($v['position_id'],true));

                $total_score = 0;
                foreach ($cate_data as  $key=>$val){

                    foreach ($position as  $p_key=>$p_val){

                        if($val['cate_id']==$p_val){
                            $val['score'] = Db::name('answer_record')->where('teacher_id',$v['id'])->where('performance_cate_id',$p_val)
                                ->where('status',1)->where('check_time',['>=',$start_time],['<',$end_time])->value('score');
                            if($val['score']==null){
                                $val['score'] = '暂未通过审核';
                            }else{
                                $total_score += $val['score'];
                            }
                        }else{
                            $val['score'] = '未参与';
                        }
                    }
                    $teacher_data['data'][$k]["title{$val['cate_id']}"] = $val['score'];
                }

                $teacher_data['data'][$k]['total_score'] =$total_score;
                $teacher_score[] = (float)$total_score;
            }

            //排名
            rsort($teacher_score);
            foreach ($teacher_data['data'] as $t_k=>$t_v){

                foreach ($teacher_score as $k=>$v){

                    if($v==$t_v['total_score']){
                        $teacher_data['data'][$t_k]['sort'] = $k+1;
                        break;
                    }

                }

            }

            $is_all = input('post.all');
            //是否获取全部
            if(!isset($is_all)&&input('post.all')!=1){
                //分页教师列表
                $teacher_data_page = Db::name('teacher t')
                    ->join("section s", "s.section_id=t.section_id", 'left')
                    ->field("t.id,t.teacher_no,t.true_name,t.position_id,s.title as section_name,s.section_id")
                    ->where('t.is_del',0)
                    ->where($map)
                    ->where('t.true_name|t.teacher_no', 'like', "%" . $teacher_keywoed . "%")
                    ->where('t.id','neq',1)
                    ->paginate(['list_rows'=>$pageSize,'page'=>$page])
                    ->toArray();

                if(!isset($teacher_data_page['data'])||empty($teacher_data_page['data'])){
                    return $result = ['code' => 0, 'msg' => '成功!', 'data' => '', 'count' =>''];
                }

                foreach ($teacher_data_page['data'] as $k=>$v){

                    $temp_page[$v['id']] = $v;

                }

                $teacher_data_page['data'] = array();
                $teacher_data_page['data'] = $temp_page;

                foreach ($teacher_data['data'] as $s_k=>$s_v){

                    foreach ($teacher_data_page['data']  as $k=>$v){

                        if($v['id']==$s_v['id']){

                            $teacher_data_page['data'][$k] = $s_v;

                        }

                    }

                }

                $teacher_data['data'] =  $teacher_data_page['data'];

            }


            return $result = ['code' => 0, 'msg' => '成功!', 'data' => $teacher_data['data'], 'count' =>$teacher_data['total']];
        }

        //周期数据
        $cycle_data = Db::name('cycle')->select();

        //考核项分类
        $cate_data =  Db::name('performance_cate')->field("cate_id,title,cycle_id")->where('is_del',0)->select();

        //部门
        $section_data = Db::name('section')->field('section_id,title')->where('is_del',0)->select();
        $this->assign('cate_data',$cate_data);
        $this->assign('section_data',$section_data);
        $this->assign('cycle_data',$cycle_data);
        return $this->fetch('person_list');
    }

    /**部门绩效
     * @return array|mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function sectionList(){

        if (request()->isAjax()) {

            $page =input('page',1);
            $pageSize =input('limit',config('pageSize'));

            //部门关键字
            $section_keyword = trim(input('post.section_keyword'));
            //周期id
            $cycle_cate = (int)trim(input('post.cycle_cate'));
            //周期关键字1
            $c1 = trim(input('post.cycle_1'));
            //周期关键字2
            $c2 = trim(input('post.cycle_2'));


//        默认开始时间 当前月份一号
            $start_time = strtotime(date('Y-m',  time()).'-01');
//        默认结束时间 当前时间
            $end_time = time();

            //月度
            if($cycle_cate==1){
                $cycle_data = Db::name('cycle')->where('id',1)->find();
                $start_time = strtotime($c1.'-'.$cycle_data['start_time']);
                $end = $c1.'-'.$cycle_data['end_time'];
                $end_time = strtotime( "$end +1 day");
//学期
            }elseif ($cycle_cate==2){

                $cycle_data = Db::name('cycle')->where('id',2)->find();
                $cycle_data_start_time = unserialize($cycle_data['start_time']);
                $cycle_data_end_time = unserialize($cycle_data['end_time']);
                $start_time = strtotime($c1.'-'.$cycle_data_start_time[$c2-1]);
                $end = $c1.'-'.$cycle_data_end_time[$c2-1];
                $end_time = strtotime( "$end +1 day");

//年度
            }elseif ($cycle_cate==3){
                $cycle_data = Db::name('cycle')->where('id',3)->find();
                $start_time = strtotime($c1.'-'.$cycle_data['start_time']);
                $end = $c1.'-'.$cycle_data['end_time'];
                $end_time = strtotime( "$end +1 day");

            }

            //拿到全部部门
            $section_data = Db::name('section')
                ->field("title as section_name,section_id")
                ->where('is_del',0)
                ->select();

            if(!$section_data){
                return $result = ['code' => 0, 'msg' => '成功!', 'data' => '', 'count' =>''];
            }

            //将section_id的值装换为key值
            foreach ($section_data as $k=>$v){

                $temp[$v['section_id']] = $v;

            }

            $count = count($section_data);
            $section_data['data'] = $temp;
            $section_data['total'] = $count;

            //全部教师列表
            $teacher_data = Db::name('teacher t')
                ->join("section s", "s.section_id=t.section_id", 'left')
                ->field("t.id,t.teacher_no,t.true_name,t.position_id,s.title as section_name,s.section_id")
                ->where('t.is_del',0)
                ->where('t.id','neq',1)
                ->select();

            if(!$teacher_data){
                return $result = ['code' => 0, 'msg' => '成功!', 'data' => $section_data['data'], 'count' =>$section_data['total']];
            }

            //全部考核项分类
            $cate_data =  Db::name('performance_cate')->field("cate_id,title,cycle_id")->where('is_del',0)->select();

            if(!$cate_data){
                return $result = ['code' => 0, 'msg' => '成功!', 'data' => $section_data['data'], 'count' =>$section_data['total']];
            }

            //拿到所有部门总成绩以及排名
            foreach ($section_data['data'] as $s_k=>$s_v){

                foreach ($teacher_data as $k=>$v) {

                    if (isset($v['section_id'])&&isset($s_v['section_id'])&&$v['section_id'] == $s_v['section_id']) {

                        //职务数据
                        $position = array_keys(json_decode($v['position_id'], true));

                        $total_score = 0;

                        foreach ($cate_data as $key => $val) {

                            foreach ($position as $p_key => $p_val) {

                                if (isset($val['cate_id'])&&$val['cate_id'] == $p_val) {

                                    $val['score'] = Db::name('answer_record')->where('teacher_id', $v['id'])->where('performance_cate_id', $p_val)
                                        ->where('status', 1)->where('check_time',['>=',$start_time],['<',$end_time])->value('score');

                                    if ($val['score'] == null) {
                                        $val['score'] = 0;
                                    } else {
                                        $total_score += (float)$val['score'];
                                    }

                                } else {

                                    $val['score'] = 0;

                                }

                            }


                            if (isset($section_data['data'][$s_k]["title{$val['cate_id']}"])) {
                                $section_data['data'][$s_k]["title{$val['cate_id']}"] = $section_data['data'][$s_k]["title{$val['cate_id']}"] + (float)$val['score'];
                            } else {
                                $section_data['data'][$s_k]["title{$val['cate_id']}"] = (float)$val['score'];
                            }

                        }

                        if(isset($section_data['data'][$s_k]["total_score"])){
                            $section_data['data'][$s_k]["total_score"] =  $section_data['data'][$s_k]["total_score"] + $total_score;
                        }else{
                            $section_data['data'][$s_k]["total_score"] = $total_score;
                        }

                    }
                }

                $section_score[] = (float)$section_data['data'][$s_k]["total_score"];

            }

            //排名
            rsort($section_score);
            foreach ($section_data['data'] as $s_k=>$s_v){

                foreach ($section_score as $k=>$v){

                    if($v==$s_v['total_score']){
                        $section_data['data'][$s_k]['sort'] = $k+1;
                        break;
                    }

                }

            }

            $is_all = input('post.all');
            //是否获取全部
            if(!isset($is_all)&&input('post.all')!=1){
                //分页部门列表
                $section_data_page = Db::name('section')
                    ->field("title as section_name,section_id")
                    ->where('is_del',0)
                    ->where('title', 'like', "%" . $section_keyword . "%")
                    ->paginate(['list_rows'=>$pageSize,'page'=>$page])
                    ->toArray();

                if(!isset($section_data_page['data'])||$section_data_page['data']==""){
                    return $result = ['code' => 0, 'msg' => '成功!', 'data' => '', 'count' =>''];
                }

                foreach ($section_data_page['data'] as $k=>$v){

                    $temp_page[$v['section_id']] = $v;

                }

                $section_data_page['data'] = array();
                $section_data_page['data'] = $temp_page;

                foreach ($section_data['data'] as $s_k=>$s_v){

                    foreach ($section_data_page['data']  as $k=>$v){

                        if($v['section_id']==$s_v['section_id']){

                            $section_data_page['data'][$k] = $s_v;

                        }

                    }

                }
                $section_data['data'] =  $section_data_page['data'];
            }

            return $result = ['code' => 0, 'msg' => '成功!', 'data' => $section_data['data'], 'count' =>$section_data['total']];

        }

        //周期数据
        $cycle_data = Db::name('cycle')->select();
        //考核项分类
        $cate_data =  Db::name('performance_cate')->field("cate_id,title,cycle_id")->where('is_del',0)->select();

        $this->assign('cate_data',$cate_data);
        $this->assign('cycle_data',$cycle_data);
        return $this->fetch('section_list');
    }


    //考核项在线测试
    public function online_test(){

        if (request()->isAjax()){

            //考核项id
            $title_id = (int)trim(input('get.title_id'));
            //获取参数
            $data = input('post.');
//            计算总分
            $total_score = 0;
            $jisuan = new Calculate();
            foreach ($data as $key=>$val){
                $total_score = call_user_func_array(array($jisuan,'timu'.$title_id),$val);
            }

            $this->success('测试结果为：'.$total_score,'',$title_id);

        }else{

            $title_id = (int)input('get.title_id');

            $info = Db::name('performance')->where('title_id',$title_id)->find();
            $info['var_content'] = json_decode($info['var_content'],true);

            $this->assign('info',$info);

            return $this->fetch('online_test');
        }


    }



    //说明
    public function instruction(){
        return view('instruction');
    }


}